<template>
    <el-main>
        <span>当前用户：{{ username }}</span>
        <el-scrollbar class="content">
            
            <ul class="msgBox" style="max-width: 480px" id="message" v-for="msg in state.messages" :key="msg.id">
                <li v-for="msg in state.messages" :key="msg.id" >
                    <el-col v-if="msg.username === user" :class="msg.username === username ? 'whoSend' : ''">
                        <span>{{ msg.content }} -- my {{ msg.username }}</span>
                        <!-- <span>{{ msg.username }}</span> -->
                    </el-col>
                    <el-col v-else class="otherMsg" :class="msg.username === username ? 'mySendMsgBox' : ''">
                        <div class="mySendMsgBgc mySendMsg">
                            <span> {{ msg.content }} -- other </span>
                        </div>

                    </el-col>
                </li>
                <!-- <el-row >
                    <el-icon><Avatar /></el-icon>

                    <el-col class="user" :span="8">
                    <span>{{ msg.user }}</span>
                    </el-col>
                    <el-col class="content" :span="18">
                    <span>{{ msg.content}}</span>
                    </el-col>
                </el-row> -->
            </ul>
            
        </el-scrollbar>
        <div class="msgSend" @onsubmit="sendMessage" @submit.prevent>
            <el-input type="textarea" class="messageText" v-model="state.message" @keyup.enter="sendMessage" placeholder="Please input" />
            <el-button type="primary" plain @click="sendMessage">send</el-button>
            <el-button type="primary" plain @click="exitChat">exit</el-button>
        </div>
    </el-main>
</template>

<script setup>
import { inputEmits } from 'element-plus'
import { onBeforeUnmount, onMounted, ref, reactive, watch } from 'vue'
import { useStore } from 'vuex'
import useWebSocket from '@/hooks/useWebSocket'

// import { User } from '@element-plus/icons-vue'
// import { CollaborationSocket } from '@/utils/socket.js'
let props = defineProps({
    login: {
        type: Boolean,
        default: false
    },
    username: {
        type: String,
        default: ""
    }
})

let emit = defineEmits(["exitChat"])

let store = useStore()
let ws = useWebSocket(handleMessage)
let state = reactive({
    message: '',
    messages: [],
})
let isConnected = false
let size = "default"


onMounted(()=>{
    console.log(`${props.username} enter chat! `)
    if (props.login) {
        if (store.getters.getWsConnections.length === 0) {
            console.log("连接不存在, 创建新连接")
            initWebsocket()
        } else {
            // 获取当前已存在的连接信息，若存在则直接使用
            for (let i = 0; i < store.getters.getWsConnections.length; i++) {
                if (store.getters.getWsConnections[i].readyState === WebSocket.OPEN) {
                    console.log("连接已存在, 直接使用")
                    ws = store.getters.getWsConnections[i]
                }
            }
        }
    }
    
})

function initWebsocket() {

    // 打开ws连接
    // ws = new WebSocket(url);
    // ws.onopen = () => {
    //     isConnected = true;
    //     store.getters.getWsConnections.push(ws)
    //     console.log("websocket connected")
    //     console.log("ws info", store.getters.getWsConnections)
    // };
    // ws.onmessage = (event) => {
    //     // console.log("event.data: ", event.data)
    //     const data = JSON.parse(event.data);  // 解析接收到的消息数据
    //     // console.log("data: ", data)
    //     messages.value.push(data);   // 更新相应式数据以触发视图更新
    //     scrollToBottom()
    //     // console.log("messages: ", messages)
    // };
    // ws.onerror = (error) => {
    //     console.error('websocket error', error);
    // };
    // ws.onclose = (event) => {
    //     isConnected = false;
    //     console.log('websocket closed', event.reason);
    // };


    // 方式二
    // const socket = new CollaborationSocket(
    //     'ws://127.0.0.1:8080',
    //     'chat',
    //     'zhangsan',
    //     '0'
    // )
    // socket.connect()

    // // 监听聊天消息
    // socket.on("0", (message)=>{
    //     console.log('message: ', message)
    //     messages.push(message.message)
    //     scrollToBottom()
        
    // })
}

function handleMessage(event) {
    // 解析接收到的消息数据
    const data = JSON.parse(event.data);
    state.messages.push(data)
    console.log('message: ', event.data)
}

const sendMessage = () => {
    if (state.message) {
        ws.send(JSON.stringify({
            user_id: props.username,
            username: props.username,
            content: state.message,
            dateTime: new Date().toLocaleString()
        }), props.username);
    }
    state.message = '';
}

watch(state.messages, () => {
    const content = document.querySelector('.content')
    setTimeout(() => {
        content.scrollTop = content.scrollHeight;
    }, 100);
})

function exitChat() {
    emit("exitChat")
}

</script>


<style scoped>
.el-main {
    position: fixed;
    top: 100px;
    left: 200px;
    width: auto;
    height: 800px;
    padding: 10px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    margin: 10px;
    border: 0.3px solid #ccc;
}

.content {
    width: 800px;
    height: 600px;
    /* overflow: auto; */
    /* display: flex; */
    /* flex-direction: column; */
    margin: 10px 20px 10px 20px;
    border-radius: 10px;
    background-color: var(--el-color-primary-light-9);
    /* border: 0.1px solid #ccc; */
}

.msgBox {
    /* height: 550px; */
    width: 100%;
    overflow: auto;
}

.msgBox li {
    /* margin-bottom: 15px;
    max-width: 70%;
    clear: both; */
    margin-top: 20px;
}

.whoSend {
    text-align: end;
    display: flex;
    flex-direction: column;
}

.otherMsg {
    display: flex;
    padding: 10px;
    margin-top: 10px;
}

.mySendMsgBox {
    /* display: flex; */
    /* justify-content: end; */
    background-color: #ccc;
    color: #000;
}

.mySendMsgBgc {
    border-radius: 10px;
    padding: 10px;
    /* background-color: #95ec69; */
    background-color: #409eff;
    color: #fff;
}

.msgSend {
    color: #ccc;
    width: 100%;
    /* height: 100%; */
    padding: 10px;
    margin: 0;
}

.msgSend .messageText {
    width: 100%;
    height: 80%;
    /* border: 0.1px solid #c8c7c7; */
    border-radius: 5px;
    padding: 5px;
}

.msgs .el-button {
    position: absolute;
    bottom: 5px;
    right: 10px;
}


/* .content {
    word-wrap: break-word;
    padding: 10px;
    margin: 10px 10px 10px 30px;
    text-align: left;
    border-radius: 10px;
    background-color: var(--el-color-primary-light-9);
}
.msg-l .msg-l.content {
    background-color: #f1f1f1;
    color: #333;
}
.msg-r {
    float: right;
    text-align: right;
}
.msg-r .msg-r.content {
    background-color: #409eff;
    color: white;
}
.el-main {
    height: 650px;
    
}
.el-scrollbar {
    height: 500px;
}
.el-icon {
    border: 1px solid black;
    margin: 5px;
    padding: 5px;
}
.user {
    text-align: left;
    margin: 5px 15px;
    color: grey;
} */

</style>